/* eslint-disable import/no-anonymous-default-export */
/* eslint-disable jsx-a11y/anchor-is-valid */

export const putFile = (file)=>{
    if( !file ){
        throw new Error("需要传入一个file对象");
    }

    const filename = file.name;
    let host='', key=''

    return new Promise((resolve, reject)=>{
        fetch("/api/get_post_signature_for_oss_upload", { method: "GET" })
            .then((response) => {
                if (!response.ok) {
                    throw new Error("获取签名失败");
                }
                return response.json();
            })
            .then((data) => {
                key = data.dir + crypto.randomUUID() + file.name;
                let formData = new FormData();
                formData.append("success_action_status", "200");
                formData.append("policy", data.policy);
                formData.append("x-oss-signature", data.signature);
                formData.append("x-oss-signature-version", "OSS4-HMAC-SHA256");
                formData.append("x-oss-credential", data.x_oss_credential);
                formData.append("x-oss-date", data.x_oss_date);
                formData.append("key", key); // 文件名
                formData.append("x-oss-security-token", data.security_token);
                formData.append("file", file); // file 必须为最后一个表单域

                host = data.host

                return fetch(data.host, { 
                    method: "POST",
                    body: formData
                });
            })
            .then((response) => {
                if (response.ok) {
                    console.log("上传成功");
                    const fileUrl = `${host}/${key}`;
                    console.log('file: ', fileUrl)
                    // J_img.src = fileUrl
                    resolve(fileUrl)
                    // alert("文件已上传: "+fileUrl);
                } else {
                    console.log("上传失败", response);
                    // alert("上传失败，请稍后再试");
                    reject(response);
                }
            })
            .catch((error) => {
                console.error("发生错误:", error);
                reject(error)
            });
    });
}

export const getFile = (assetsUrl)=>{
    
}